package com.soul.dubbo.api.mongo;

import com.soul.model.mongo.Friend;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

/**
 * @author mdoya
 * @version 1.0
 * @description:
 */
@Slf4j
@DubboService
public class FriendApiImpl implements FriendApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     *  添加练习好友关系
     * @param friendUserId 好友id
     * @param userid 用户id
     */
    @Override
    public void addContacts(Long friendUserId, Long userid) {
        // 用户添加佳人为好友
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userid).and("friendId").is(friendUserId));
        if (!mongoTemplate.exists(query, Friend.class)){
            commonAddContacts(friendUserId, userid);
        }
        // 佳人添加为用户好友
        Query query2 = new Query();
        query.addCriteria(Criteria.where("userId").is(friendUserId).and("friendId").is(userid));
        if (!mongoTemplate.exists(query2, Friend.class)){
            commonAddContacts(friendUserId, userid);
        }
    }

    private void commonAddContacts(Long friendUserId, Long userid) {
        Friend friend = new Friend();
        friend.setFriendId(friendUserId);
        friend.setUserId(userid);
        friend.setCreated(System.currentTimeMillis());
        mongoTemplate.insert(friend);
    }
}
